<?php

class AccountController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(), array(
			'setReturnUrl + login',
		));
	}

	function filterSetReturnUrl(CFilterChain $chain)
	{
		$returnUrl = Yii::app()->request->getParam('returnUrl',null);
		if(!empty($returnUrl))
			Yii::app()->user->returnUrl = $returnUrl;

		//Nếu đăng nhập rồi thì tự động redirect luôn về returnUrl
		if(!empty(Yii::app()->user->id))
			Yii::app()->getController()->redirect(Yii::app()->user->returnUrl);

		$chain->run();
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('register','captcha','login'),
				'users'=>array('*'),
			),
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('signOut'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Declares class-based actions.
	 */
	public function actions() {
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha' => array(
				'class' => 'CCaptchaAction',
//				'transparent' => true,
				'foreColor' => 0xFF0000,
			),
		);
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionRegister()
	{
		/**
		 * @var $model Account
		 */
		$model=new Account;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Account']))
		{
			$model->attributes=$_POST['Account'];
			$model->captcha = isset($_POST['Account']['captcha']) ? $_POST['Account']['captcha'] : null;
			if($model->validate()){
				if($model->createAccount()){
					Yii::app()->user->setFlash('success','Chaò '. $model->email .'! Bạn đã đăng ký thành công');
					$this->refresh();
				}else{
					Yii::app()->user->setFlash('error','Hệ thống tạm thời tạm dừng tính năng đăng ký tài khoản');
				}
			}else{
				Yii::app()->user->setFlash('error',CHtml::errorSummary($model));
			}
		}

		$this->render('register',array(
			'model'=>$model,
		));
	}

	public function actionLogin(){
		$model=new LoginForm;

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			if($model->validate()){
				/**
				 * @var $acc Account
				 */
				$acc = Account::model()->findByAttributes(array('email'=>$model->username));
				if (is_null($acc)){
					$this->onAccountNotFound($model->username);
				}else{
					switch ($acc->status) {
						case Account::STATUS_INIT:
							return $this->onAccountInactive($acc);
						case Account::STATUS_LOCKED:
							Yii::app()->user->setFlash('error', Yii::t('message', 'Tài khoản của bạn đang bị khóa!'));
							break;
						case Account::STATUS_VERIFIED:
							if (md5($model->password) == $acc->password) return $this->doLogin($acc);
							Yii::app()->user->setFlash('error', Yii::t('message', 'Mật khẩu đăng nhập sai'));
							break;
					}
				}
			}
		}

		// display the login form
		$this->render('login',array('model'=>$model));
	}

	public function actionSignOut(){
		Yii::app()->user->logout();
		$this->redirect('/');
	}

	protected function onAccountInactive(Account $acc)
	{
		Yii::app()->user->setFlash('error','Tài khoản của bạn chưa được kích hoạt!');
		$this->refresh();
	}

	protected function onAccountNotFound($username)
	{
		Yii::app()->user->setFlash('error', Yii::t('message', $username . ' không tồn tại trên hệ thống!'));
	}

	protected function doLogin(Account $acc)
	{
		$ui = new UserIdentity($acc->email, $acc->password);
		$ui->authenticate($acc);

		Yii::app()->user->login($ui);

		Yii::app()->user->setFlash('success','Chào ' . $acc->nickname. ', bạn đã đăng nhập thành công vào hệ thống!');

		$this->render('success',array('account'=>$acc));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Account::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
